import { GraphConfigData, type NodeData } from "@logicflow/core"
import { GroupNode } from '@logicflow/extension';


class MyGroupModel extends GroupNode.model {

    initNodeData(data: any) {
        super.initNodeData(data);

        this.isRestrict = true;
        this.foldable = true;
        this.resizable = true;
        this.foldedWidth = 90;
        this.foldedHeight = 60;
        
        this.width = this.properties.width || 500
        this.height = this.properties.height || 300

        //保证重新加载数据时，折叠的分组还是折叠的
        if (this.isFolded) {
            setTimeout(() => {
                this.foldGroup(true);
            });
            this.isFolded = false;//调用foldGroup会改变isFolded，提前修改保证最后数据不变
        }
    }
    //foldGroup重构解决了group的锚点在折叠的时候有延迟的情况
    foldGroup(isFolded: any) {
        super.foldGroup(isFolded);
        this.setAttributes();
    }

    setAttributes(): void {
        this.anchorsOffset = [
            [this.width / 2, 0],
            [0, this.height / 2],
            [-this.width / 2, 0],
            [0, -this.height / 2],
        ]
    }

    getAnchorStyle(anchorInfo: any) {
        const style = super.getAnchorStyle(anchorInfo);
        style.stroke = '#000';
        style.fill = '#fff';
        style.hover.fill = '#aaa';
        style.hover.stroke = '#eee';
        return style;
    }

    //children直接换成flowdata
    getData(): NodeData {
        const properties = this.getProperties()
        const data: NodeData = super.getData();
        const flowData: GraphConfigData = { nodes: [], edges: [] };
        data.sourceNodeIds = []
        data.targetNodeIds = []
        const inGroup: Record<string, boolean> = {}

        data.children.forEach((childId: string) => {
            inGroup[childId] = true;
        });
        data.children.forEach((childId: string) => {
            const model = this.graphModel.getNodeModelById(childId);
            flowData.nodes.push(model.getData());
            flowData.edges.push(...model.incoming.edges.filter(edge => inGroup[edge.sourceNodeId]).map(edge => edge.getData()));

            // 将连接到GROUP内部的边连接到GROUP
            data.sourceNodeIds.push(...model.incoming.nodes.filter(node => !inGroup[node.id]).map(node => node.id));
            data.targetNodeIds.push(...model.outgoing.nodes.filter(node => !inGroup[node.id]).map(node => node.id));
        });

        data.sourceNodeIds = Array.from(new Set(data.sourceNodeIds))
        data.targetNodeIds = Array.from(new Set(data.targetNodeIds))
        data.flowData = flowData


        data.properties = properties
        //保存折叠之前的宽高
        if (properties.isFolded) {
            data.x = this.x + this.unfoldedWidth / 2 - this.foldedWidth / 2;
            data.y = this.y + this.unfoldedHight / 2 - this.foldedHeight / 2;
        }
        return data;
    }
}

export default {
    type: "GROUP",
    view: GroupNode.view,
    model: MyGroupModel
};